package com.gf.snoopy.service;

import java.util.List;
import java.util.concurrent.Callable;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.gf.snoopy.domain.Buyer;
import com.gf.snoopy.dto.BuyerDto;
import com.gf.snoopy.mapper.BuyerMapper;
import com.gf.snoopy.platform.exception.PokeErrorCode;
import com.gf.snoopy.platform.exception.PokeException;
import com.gf.snoopy.util.ConvertUtil;
import com.gf.snoopy.util.page.Page;
import com.gf.snoopy.util.page.PagedList;
import com.gf.snoopy.util.page.PaginationUtil;

@Service
public class BuyerService {
	
	@Resource
	private BuyerMapper buyerMapper;
	
	/**
	 * 分页查询项目下的子项目
	 * @param projectId
	 * @param query
	 * @param page
	 * @return
	 * @throws PokeException
	 */
	public PagedList<BuyerDto> getProjectPage(BuyerDto query,Page page) throws PokeException{
		if(query==null || page==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"查询参数错误");
		}
		final Buyer dbQuery = ConvertUtil.convert(query,Buyer.class);
		PagedList<Buyer> voteInCondition =  PaginationUtil.pagedQuery(page, new Callable<List<Buyer>>() {            
            public List<Buyer> call() throws Exception {
                return buyerMapper.queryByCondition(dbQuery);
            }
        });
		
		return new PagedList<BuyerDto>(voteInCondition.getPage(),
				ConvertUtil.convertList(voteInCondition.getList(),
						BuyerDto.class));
	}
	
	/**
	 * 新增记录
	 * @param data
	 * @throws PokeException
	 */
	public void save(BuyerDto data) throws PokeException{
		Buyer convert = ConvertUtil.convert(data, Buyer.class);
		if(convert==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"subProject数据出错");
		}
		buyerMapper.insert(convert);
	}
	
	/**
	 * 更新记录
	 * @param data
	 * @throws PokeException
	 */
	public void update(BuyerDto data) throws PokeException{
		Buyer convert = ConvertUtil.convert(data, Buyer.class);
		if(convert==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"subProject数据出错");
		}
		buyerMapper.updateByPrimaryKeySelective(convert);
	}
	
	/**
	 * 查找结果
	 * @param id
	 * @return
	 * @throws PokeException
	 */
	public BuyerDto findById(Integer id) throws PokeException{
		if(id==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"查询的subProjectId为空");
		}
		Buyer project = buyerMapper.selectByPrimaryKey(id);
		return ConvertUtil.convert(project, BuyerDto.class);
	}
	
	/**
	 * 根据Id删除记录
	 * @param id
	 * @throws PokeException
	 */
	public void deleteById(Integer id) throws PokeException{
		if(id==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"删除的subProjectId为空");
		}
		buyerMapper.deleteByPrimaryKey(id);
	}
	
}
